#include "message_main_push.h"

MessagePusher::MessagePusher(IMessageSync* s) : QObject(), m_sync(s) {
  if (s) s->RegisterMessageDispatchObserver(this);
  connect(this, &MessagePusher::push_data, this, &MessagePusher::OnPushData);
}

MessagePusher::~MessagePusher() {
  if (m_sync) m_sync->DeRegisterMessageDispatchObserver(this);
}

void MessagePusher::OnPushData(void* data) {
  kPushData* kd = (kPushData*)data;
  if (m_sync)
    m_sync->DispatchMessage(kd->pRecvData, kd->nRecvLen, kd->flag, kd->tag);

  if (kd->pRecvData) {
    delete[] kd->pRecvData;
  }
  delete kd;
}

STDMETHODIMP_(void)
MessagePusher::PushMessage(const char* pRecvData, int nDataLen, uint32_t flag,
                           void* tag) {
  kPushData* data = new kPushData;
  data->flag = flag;
  data->tag = tag;
  data->nRecvLen = nDataLen;
  if (pRecvData && nDataLen > 0) {
    data->pRecvData = new char[nDataLen];
    memcpy(data->pRecvData, pRecvData, nDataLen);
  }

  push_data(data);
}
